import { Message, UsageInfo } from '../types';

export class HistoryManager {
  private messages: Message[] = [];
  private autoSaveCallback?: () => void; // 新增：自动保存回调
 
  constructor(systemPrompt: string) {
    this.messages.push({
      role: "system",
      content: systemPrompt
    });    
  }

  // 新增：设置自动保存回调
  setAutoSaveCallback(callback: () => void) {
    this.autoSaveCallback = callback;
  }

  addMessage(message: Message) {
    this.messages.push(message);
    
    // 新增：每次添加消息后自动保存
    if (this.autoSaveCallback) {
      try {
        this.autoSaveCallback();
        console.log('💾 消息已添加并自动保存');
      } catch (error) {
        console.error('❌ 自动保存失败:', error);
      }
    }
  }

  addUserMessage(content: string) {
    this.addMessage({
      role: 'user',
      content
    });
  }

  addAssistantMessage(content: string, toolCalls?: any[], usage?: UsageInfo, reasoning?: string) {
    const message: Message = {
      role: 'assistant',
      content,
      reasoning, // 添加reasoning字段
      tool_calls: toolCalls,
      usage: usage  // 添加usage信息
    };
    
    this.addMessage(message);
  }

  addToolMessage(toolCallId: string, content: string) {
    this.addMessage({
      role: 'tool',
      content,
      tool_call_id: toolCallId
    });
  }

  getMessages(): Message[] {
    return [...this.messages]; // 保持原始时间顺序
  }

  getLastUserMessage(): Message | undefined {
    for (let i = this.messages.length - 1; i >= 0; i--) {
      if (this.messages[i].role === 'user') {
        return this.messages[i];
      }
    }
    return undefined;
  }

    removeLastConversation() {
      if (this.messages.length <= 1) {
        return false; // 保留系统消息
      }

      // 从后往前删除，直到找到用户消息
      const messagesToRemove: number[] = [];
      
      for (let i = this.messages.length - 1; i >= 1; i--) {
        messagesToRemove.push(i);
        
        if (this.messages[i].role === 'user') {
          break;
        }
      }

      // 删除消息
      messagesToRemove.forEach(() => {
        this.messages.pop();
      });

      return true;
    }

    clear() {
      const systemMessage = this.messages[0];
      this.messages = [systemMessage];
    }

  updateSystemPrompt(systemPrompt:string) {
    if (this.messages.length > 0 && this.messages[0].role === 'system') {
      this.messages[0].content = systemPrompt;
      console.log('系统提示词已更新');
    }
  }

  getConversationCount(): number {
    return this.messages.filter(msg => msg.role === 'user').length;
  }

  getTokenCount(): number {
    // 简单的token估算 (实际使用时可以集成更准确的tokenizer)
    return this.messages.reduce((count, msg) => {
      return count + Math.ceil(msg.content.length / 4);
    }, 0);
  }

  // 获取usage统计 - 从messages中计算
  getTotalUsage(): {
    totalPromptTokens: number;
    totalCompletionTokens: number;
    totalTokens: number;
    totalCost: number;
    totalReasoningTokens: number;
    totalCachedTokens: number;
  } {
    return this.messages
      .filter(msg => msg.role === 'assistant' && msg.usage)
      .reduce((total, msg) => {
        const usage = msg.usage!;
        return {
          totalPromptTokens: total.totalPromptTokens + usage.prompt_tokens,
          totalCompletionTokens: total.totalCompletionTokens + usage.completion_tokens,
          totalTokens: total.totalTokens + usage.total_tokens,
          totalCost: total.totalCost + (usage.cost || 0),
          totalReasoningTokens: total.totalReasoningTokens + (usage.reasoning_tokens || 0),
          totalCachedTokens: total.totalCachedTokens + (usage.cached_tokens || 0)
        };
      }, {
        totalPromptTokens: 0,
        totalCompletionTokens: 0, 
        totalTokens: 0,
        totalCost: 0,
        totalReasoningTokens: 0,
        totalCachedTokens: 0
      });
  }

  // 获取最近的usage信息 - 从最后的assistant消息获取
  getLastUsage(): UsageInfo | undefined {
    for (let i = this.messages.length - 1; i >= 0; i--) {
      if (this.messages[i].role === 'assistant' && this.messages[i].usage) {
        return this.messages[i].usage;
      }
    }
    return undefined;
  }

  // 获取所有usage历史 - 从messages中提取
  getUsageHistory(): UsageInfo[] {
    return this.messages
      .filter(msg => msg.role === 'assistant' && msg.usage)
      .map(msg => msg.usage!);
  }

}